package org.jwt.servlet;

import com.google.gson.Gson;
import org.jwt.dto.ResultVO;
import org.jwt.utils.GsonUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author zqx
 * @date 2021-11-19
 */
public class BaseServlet extends HttpServlet {
    public ResultVO successJson(Object value) {
        ResultVO resultVo = new ResultVO();
        resultVo.setData(value);
        return resultVo;
    }

    public ResultVO successJson(Object value, int code, String msg) {
        ResultVO resultVo = new ResultVO();
        resultVo.setData(value);
        resultVo.setCode(code);
        resultVo.setMsg(msg);
        return resultVo;
    }

    public ResultVO successJson() {
        return new ResultVO();
    }

    public ResultVO errorJson() {
        ResultVO resultVo = new ResultVO();
        resultVo.setCode(500);
        resultVo.setMsg("系统繁忙，请稍后再试!");
        return resultVo;
    }

    public ResultVO errorJson(int code, String msg) {
        ResultVO resultVo = new ResultVO();
        resultVo.setCode(code);
        resultVo.setMsg(msg);
        return resultVo;
    }

    public ResultVO errorJson(String msg) {
        ResultVO resultVo = new ResultVO();
        resultVo.setCode(500);
        resultVo.setMsg(msg);
        return resultVo;
    }

    public Map<String,String> getParameterMap(HttpServletRequest req) throws IOException {
        BufferedReader reader = req.getReader();
        String str = null ;
        String jsonParams = "" ;

        while((str=reader.readLine())!=null) {
            // 把读取的数据，串联起来
            jsonParams = jsonParams + str ;
        }

        return GsonUtil.parseMap(jsonParams) ;
    }

    public void print(HttpServletResponse resp, ResultVO resultVO) throws IOException{
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.print(new Gson().toJson(resultVO));
        out.flush();
        out.close();

    }
}
